﻿using Common.Api.Client;

namespace Cyss.TaskControl.Infrastructure
{

    /// <summary>
    /// 日志变更委托
    /// </summary>
    public delegate void LogsChangeEventHander(int id);

    public class LoggingManager
    {
        /// <summary>
        /// 日志变更事件
        /// </summary>
        public static event LogsChangeEventHander LogsChangeEvent;
        private static object lockObject = new object();
        public static List<TaskLogging> GetLoggins(int TaskId)
        {
            return Loggings.Where(x => x.TaskId == TaskId).OrderByDescending(x => x.CreateTime).ToList();
        }

        private static List<TaskLogging> Loggings { set; get; }

        static LoggingManager()
        {
            Loggings = new List<TaskLogging>();
        }

        public static void Insert(TaskLogging taskLogging)
        {
            lock (lockObject)
            {
                if (Loggings.Count(x => x.TaskId == taskLogging.TaskId) >= 200)
                {
                    var clears = Loggings.Where(x => x.TaskId == taskLogging.TaskId).OrderByDescending(x => x.CreateTime).Skip(200).ToList();
                    clears.ForEach(x => Loggings.Remove(x));
                    clears = null;
                }
                Loggings.Add(taskLogging);
            }
            LogsChangeEvent?.Invoke(taskLogging.TaskId);
            insesrtDatabase(taskLogging);
        }

        private async static void insesrtDatabase(TaskLogging taskLogging)
        {
            await CommonClientFactory.Task.CreateTaskRecord(new Common.Api.Dtos.TaskRecordModel
            {
                TaskId = taskLogging.TaskId,
                Content = taskLogging.Content,
                CreateDate = DateTime.Now,
            });
        }
    }
}
